from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.popup import Popup
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.image import Image
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.checkbox import CheckBox
from kivy.uix.spinner import Spinner
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
from kivy.core.window import Window
from kivy.storage.jsonstore import JsonStore
import json
import os
import uuid
from datetime import datetime

# 设置中文字体支持
import kivy
kivy.resources.resource_add_path('.')

class ProductManager:
    """商品管理类，处理商品的增删改查和数据持久化"""
    def __init__(self):
        # 确保data目录存在
        if not os.path.exists('data'):
            os.makedirs('data')
            
        # 确保images目录存在
        if not os.path.exists('data/images'):
            os.makedirs('data/images')
            
        # 初始化JSON存储
        self.store = JsonStore('data/products_data.json')
        self.products = {}
        self.load_products()
        
    def load_products(self):
        """从文件加载商品数据"""
        if self.store.exists('products'):
            self.products = self.store.get('products')['data']
        else:
            self.products = {}
            self.save_products()
    
    def save_products(self):
        """保存商品数据到文件"""
        self.store.put('products', data=self.products)
    
    def generate_product_id(self):
        """生成3位数字格式的商品ID"""
        max_id = 0
        for product_id in self.products:
            try:
                num_id = int(product_id)
                if num_id > max_id:
                    max_id = num_id
            except ValueError:
                continue
        new_id = max_id + 1
        return f"{new_id:03d}"
    
    def add_product(self, name, price, barcode=None, image_path=None):
        """添加新商品"""
        # 验证价格是否为数字
        try:
            price = float(price)
            if price < 0:
                return False, "价格不能为负数"
        except ValueError:
            return False, "价格必须是有效数字"
        
        # 验证条形码是否重复
        if barcode:
            for product in self.products.values():
                if product['barcode'] == barcode:
                    return False, "条形码已存在"
        
        # 生成商品ID
        product_id = self.generate_product_id()
        
        # 保存商品信息
        self.products[product_id] = {
            'id': product_id,
            'name': name,
            'price': price,
            'barcode': barcode or '',
            'image_path': image_path or ''
        }
        
        # 保存到文件
        self.save_products()
        return True, product_id
    
    def update_product(self, product_id, name, price, barcode=None, image_path=None):
        """更新商品信息"""
        # 验证商品是否存在
        if product_id not in self.products:
            return False, "商品不存在"
        
        # 验证价格是否为数字
        try:
            price = float(price)
            if price < 0:
                return False, "价格不能为负数"
        except ValueError:
            return False, "价格必须是有效数字"
        
        # 验证条形码是否重复（排除当前商品）
        if barcode:
            for pid, product in self.products.items():
                if pid != product_id and product['barcode'] == barcode:
                    return False, "条形码已存在"
        
        # 更新商品信息
        self.products[product_id]['name'] = name
        self.products[product_id]['price'] = price
        self.products[product_id]['barcode'] = barcode or ''
        if image_path is not None:
            self.products[product_id]['image_path'] = image_path
        
        # 保存到文件
        self.save_products()
        return True, "更新成功"
    
    def get_product_by_id(self, product_id):
        """通过商品ID获取商品信息"""
        return self.products.get(product_id)
    
    def get_product_by_barcode(self, barcode):
        """通过条形码获取商品信息"""
        for product in self.products.values():
            if product['barcode'] == barcode:
                return product
        return None
    
    def get_all_products(self):
        """获取所有商品信息"""
        return list(self.products.values())

class ShoppingCart:
    """购物车类，处理商品的添加、删除和结算"""
    def __init__(self):
        self.items = {}
        self.product_manager = ProductManager()
        
    def add_item(self, product_id):
        """添加商品到购物车"""
        product = self.product_manager.get_product_by_id(product_id)
        if product:
            if product_id in self.items:
                self.items[product_id]['quantity'] += 1
            else:
                self.items[product_id] = {
                    'product': product,
                    'quantity': 1
                }
            return True, f"已添加 {product['name']}"
        return False, "商品不存在"
    
    def remove_item(self, product_id):
        """从购物车移除商品"""
        if product_id in self.items:
            if self.items[product_id]['quantity'] > 1:
                self.items[product_id]['quantity'] -= 1
            else:
                del self.items[product_id]
            return True, "已移除商品"
        return False, "购物车中没有该商品"
    
    def get_items(self):
        """获取购物车中的所有商品"""
        return self.items
    
    def get_total_amount(self):
        """计算购物车总金额"""
        total = 0
        for item in self.items.values():
            total += item['product']['price'] * item['quantity']
        return total
    
    def get_total_items(self):
        """计算购物车中的商品总数"""
        total = 0
        for item in self.items.values():
            total += item['quantity']
        return total
    
    def clear(self):
        """清空购物车"""
        self.items = {}
    
    def generate_receipt(self):
        """生成收据信息"""
        receipt = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'items': [],
            'total_items': self.get_total_items(),
            'total_amount': self.get_total_amount()
        }
        
        for item in self.items.values():
            product = item['product']
            subtotal = product['price'] * item['quantity']
            receipt['items'].append({
                'name': product['name'],
                'price': product['price'],
                'quantity': item['quantity'],
                'subtotal': subtotal
            })
        
        return receipt

class ProductRegistrationPopup(Popup):
    """商品注册弹窗"""
    def __init__(self, product_manager, callback=None, product_id=None, **kwargs):
        super(ProductRegistrationPopup, self).__init__(**kwargs)
        self.size_hint = (0.9, 0.8)
        self.title = "注册新商品" if not product_id else "修改商品信息"
        self.product_manager = product_manager
        self.callback = callback
        self.product_id = product_id
        self.image_path = None
        
        # 创建主布局
        main_layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
        
        # 创建表单布局
        form_layout = GridLayout(cols=2, spacing=10, size_hint_y=None)
        form_layout.bind(minimum_height=form_layout.setter('height'))
        
        # 商品ID
        form_layout.add_widget(Label(text='商品ID:'))
        self.id_input = TextInput(readonly=True)
        if product_id:
            self.id_input.text = product_id
        else:
            self.id_input.text = self.product_manager.generate_product_id()
        form_layout.add_widget(self.id_input)
        
        # 商品名称
        form_layout.add_widget(Label(text='商品名称:'))
        self.name_input = TextInput(multiline=False)
        form_layout.add_widget(self.name_input)
        
        # 商品价格
        form_layout.add_widget(Label(text='商品价格:'))
        self.price_input = TextInput(multiline=False, input_filter='float')
        form_layout.add_widget(self.price_input)
        
        # 商品条形码
        form_layout.add_widget(Label(text='商品条形码:'))
        self.barcode_input = TextInput(multiline=False)
        form_layout.add_widget(self.barcode_input)
        
        # 添加滚动视图
        scroll_view = ScrollView(size_hint=(1, 0.6))
        scroll_view.add_widget(form_layout)
        main_layout.add_widget(scroll_view)
        
        # 商品图片预览
        self.image_preview = Image(size_hint=(1, 0.3))
        main_layout.add_widget(self.image_preview)
        
        # 按钮布局
        button_layout = BoxLayout(size_hint_y=0.1, spacing=10)
        
        # 拍照按钮
        self.camera_button = Button(text='拍照录入')
        self.camera_button.bind(on_press=self.open_camera)
        button_layout.add_widget(self.camera_button)
        
        # 取消按钮
        cancel_button = Button(text='取消')
        cancel_button.bind(on_press=self.dismiss)
        button_layout.add_widget(cancel_button)
        
        # 注册/更新按钮
        self.submit_button = Button(text='注册' if not product_id else '更新')
        self.submit_button.bind(on_press=self.submit)
        button_layout.add_widget(self.submit_button)
        
        main_layout.add_widget(button_layout)
        self.content = main_layout
        
        # 如果是修改商品信息，加载商品数据
        if product_id:
            product = self.product_manager.get_product_by_id(product_id)
            if product:
                self.name_input.text = product['name']
                self.price_input.text = str(product['price'])
                self.barcode_input.text = product['barcode']
                self.image_path = product['image_path']
                if self.image_path and os.path.exists(self.image_path):
                    self.image_preview.source = self.image_path
                    self.image_preview.reload()
    
    def open_camera(self, instance):
        """打开相机（在实际安卓设备上会调用系统相机）"""
        # 在实际安卓应用中，这里会调用系统相机
        # 为了测试，我们创建一个文件选择器来选择图片
        popup = Popup(title="选择图片", size_hint=(0.9, 0.9))
        
        filechooser = FileChooserListView(path='.')
        filechooser.filters = ['*.png', '*.jpg', '*.jpeg']
        
        select_button = Button(text='选择', size_hint_y=None, height=40)
        
        def select_image(instance):
            if filechooser.selection:
                # 复制图片到data/images目录
                original_path = filechooser.selection[0]
                file_name = str(uuid.uuid4()) + os.path.splitext(original_path)[1]
                self.image_path = os.path.join('data/images', file_name)
                
                # 在实际应用中，这里应该复制文件
                # 由于是示例，我们直接使用原路径
                self.image_preview.source = original_path
                self.image_preview.reload()
                popup.dismiss()
                
        select_button.bind(on_press=select_image)
        
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(filechooser)
        layout.add_widget(select_button)
        
        popup.content = layout
        popup.open()
    
    def submit(self, instance):
        """提交表单"""
        name = self.name_input.text.strip()
        price = self.price_input.text.strip()
        barcode = self.barcode_input.text.strip()
        
        # 验证必填字段
        if not name:
            self.show_error("请输入商品名称")
            return
        if not price:
            self.show_error("请输入商品价格")
            return
        
        # 如果是修改商品
        if self.product_id:
            success, message = self.product_manager.update_product(
                self.product_id, name, price, barcode, self.image_path
            )
        else:
            success, message = self.product_manager.add_product(
                name, price, barcode, self.image_path
            )
        
        if success:
            self.dismiss()
            if self.callback:
                self.callback()
            # 显示成功提示
            success_popup = Popup(
                title="成功",
                content=Label(text=f"{message}"),
                size_hint=(0.6, 0.4)
            )
            success_popup.open()
            Clock.schedule_once(success_popup.dismiss, 2)
        else:
            self.show_error(message)
    
    def show_error(self, message):
        """显示错误信息"""
        error_popup = Popup(
            title="错误",
            content=Label(text=message),
            size_hint=(0.6, 0.4)
        )
        error_popup.open()

class ProductDetailPopup(Popup):
    """商品详情弹窗"""
    def __init__(self, product_manager, product_id, update_callback=None, **kwargs):
        super(ProductDetailPopup, self).__init__(**kwargs)
        self.size_hint = (0.9, 0.8)
        self.title = "商品详情"
        self.product_manager = product_manager
        self.product_id = product_id
        self.update_callback = update_callback
        
        product = self.product_manager.get_product_by_id(product_id)
        if not product:
            self.dismiss()
            return
        
        # 创建主布局
        main_layout = BoxLayout(orientation='horizontal', padding=10, spacing=10)
        
        # 左侧：商品图片
        image_layout = BoxLayout(orientation='vertical', size_hint_x=0.4)
        self.product_image = Image()
        if product['image_path'] and os.path.exists(product['image_path']):
            self.product_image.source = product['image_path']
        else:
            self.product_image.texture = self.generate_placeholder_texture()
        image_layout.add_widget(self.product_image)
        
        # 右侧：商品信息
        info_layout = BoxLayout(orientation='vertical', size_hint_x=0.6, padding=10)
        
        info_layout.add_widget(Label(text=f"商品ID: {product['id']}", font_size=16))
        info_layout.add_widget(Label(text=f"商品名称: {product['name']}", font_size=16))
        info_layout.add_widget(Label(text=f"商品价格: ¥{product['price']:.2f}", font_size=16))
        info_layout.add_widget(Label(text=f"条形码: {product['barcode'] or '无'}", font_size=16))
        
        # 按钮布局
        button_layout = BoxLayout(size_hint_y=0.2, spacing=10, pos_hint={'bottom': 0})
        
        # 修改按钮
        edit_button = Button(text='修改')
        edit_button.bind(on_press=self.edit_product)
        button_layout.add_widget(edit_button)
        
        # 关闭按钮
        close_button = Button(text='关闭')
        close_button.bind(on_press=self.dismiss)
        button_layout.add_widget(close_button)
        
        info_layout.add_widget(button_layout)
        
        main_layout.add_widget(image_layout)
        main_layout.add_widget(info_layout)
        
        self.content = main_layout
    
    def generate_placeholder_texture(self):
        """生成占位符纹理"""
        from kivy.graphics.texture import Texture
        texture = Texture.create(size=(200, 200))
        buf = bytearray([128] * 200 * 200 * 3)  # 灰色
        texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
        return texture
    
    def edit_product(self, instance):
        """打开编辑商品窗口"""
        self.dismiss()
        popup = ProductRegistrationPopup(
            self.product_manager,
            product_id=self.product_id,
            callback=self.update_callback
        )
        popup.open()

class ProductListPopup(Popup):
    """商品列表弹窗"""
    def __init__(self, product_manager, **kwargs):
        super(ProductListPopup, self).__init__(**kwargs)
        self.size_hint = (0.95, 0.95)
        self.title = "所有商品"
        self.product_manager = product_manager
        self.selected_product_id = None
        
        # 创建主布局
        main_layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
        
        # 创建表格头部
        header_layout = GridLayout(cols=4, size_hint_y=None, height=40)
        header_layout.add_widget(Label(text='商品ID', bold=True))
        header_layout.add_widget(Label(text='商品名称', bold=True))
        header_layout.add_widget(Label(text='价格', bold=True))
        header_layout.add_widget(Label(text='条形码', bold=True))
        main_layout.add_widget(header_layout)
        
        # 创建商品列表
        self.products_layout = GridLayout(cols=4, spacing=5, size_hint_y=None)
        self.products_layout.bind(minimum_height=self.products_layout.setter('height'))
        
        # 添加滚动视图
        scroll_view = ScrollView()
        scroll_view.add_widget(self.products_layout)
        main_layout.add_widget(scroll_view)
        
        # 按钮布局
        button_layout = BoxLayout(size_hint_y=0.1, spacing=10)
        
        # 查看详情按钮
        self.detail_button = Button(text='查看详情')
        self.detail_button.bind(on_press=self.view_detail)
        self.detail_button.disabled = True
        button_layout.add_widget(self.detail_button)
        
        # 关闭按钮
        close_button = Button(text='关闭')
        close_button.bind(on_press=self.dismiss)
        button_layout.add_widget(close_button)
        
        main_layout.add_widget(button_layout)
        self.content = main_layout
        
        # 加载商品列表
        self.load_products()
    
    def load_products(self):
        """加载商品列表"""
        # 清空现有列表
        self.products_layout.clear_widgets()
        
        # 添加商品到列表
        products = self.product_manager.get_all_products()
        for product in products:
            # 创建可点击的标签，用于选择商品
            id_label = Label(text=product['id'], on_touch_down=lambda instance, touch, pid=product['id']: self.select_product(instance, touch, pid))
            name_label = Label(text=product['name'], on_touch_down=lambda instance, touch, pid=product['id']: self.select_product(instance, touch, pid))
            price_label = Label(text=f"¥{product['price']:.2f}", on_touch_down=lambda instance, touch, pid=product['id']: self.select_product(instance, touch, pid))
            barcode_label = Label(text=product['barcode'] or '无', on_touch_down=lambda instance, touch, pid=product['id']: self.select_product(instance, touch, pid))
            
            self.products_layout.add_widget(id_label)
            self.products_layout.add_widget(name_label)
            self.products_layout.add_widget(price_label)
            self.products_layout.add_widget(barcode_label)
    
    def select_product(self, instance, touch, product_id):
        """选择商品"""
        if instance.collide_point(*touch.pos):
            # 清除之前的选择样式
            for child in self.products_layout.children:
                if hasattr(child, 'background_color'):
                    delattr(child, 'background_color')
                child.canvas.before.clear()
            
            # 设置当前选择样式
            self.selected_product_id = product_id
            self.detail_button.disabled = False
            
            # 高亮显示选中的行
            # 由于是网格布局，我们需要找到当前行的所有标签
            index = -1
            for i, child in enumerate(self.products_layout.children):
                if hasattr(child, 'text') and child.text == product_id:
                    index = i
                    break
            
            if index != -1:
                # 找到当前行的四个标签
                row_start = (index // 4) * 4
                for i in range(row_start, min(row_start + 4, len(self.products_layout.children))):
                    child = self.products_layout.children[i]
                    with child.canvas.before:
                        Color(0.5, 0.5, 1, 0.5)  # 浅蓝色背景
                        Rectangle(pos=child.pos, size=child.size)
    
    def view_detail(self, instance):
        """查看商品详情"""
        if self.selected_product_id:
            popup = ProductDetailPopup(
                self.product_manager,
                self.selected_product_id,
                update_callback=self.load_products
            )
            popup.open()

class ScanProductPopup(Popup):
    """扫描商品弹窗"""
    def __init__(self, product_manager, shopping_cart, update_callback=None, **kwargs):
        super(ScanProductPopup, self).__init__(**kwargs)
        self.size_hint = (0.8, 0.6)
        self.title = "扫描商品"
        self.product_manager = product_manager
        self.shopping_cart = shopping_cart
        self.update_callback = update_callback
        
        # 创建主布局
        main_layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
        
        # 输入框和扫描按钮
        input_layout = BoxLayout(spacing=10)
        self.input_field = TextInput(
            hint_text='请输入商品ID或条形码',
            multiline=False,
            focus=True
        )
        self.input_field.bind(on_text_validate=self.scan_product)
        input_layout.add_widget(self.input_field)
        
        scan_button = Button(text='扫描')
        scan_button.bind(on_press=self.scan_product)
        input_layout.add_widget(scan_button)
        
        main_layout.add_widget(input_layout)
        
        # 结果显示
        self.result_label = Label(text='', halign='center')
        main_layout.add_widget(self.result_label)
        
        # 完成按钮
        finish_button = Button(text='完成')
        finish_button.bind(on_press=self.dismiss)
        main_layout.add_widget(finish_button)
        
        self.content = main_layout
        
        # 绑定弹窗关闭事件
        self.bind(on_dismiss=self.on_dismiss)
    
    def scan_product(self, instance):
        """扫描商品"""
        input_text = self.input_field.text.strip()
        if not input_text:
            self.result_label.text = "请输入商品ID或条形码"
            return
        
        # 尝试通过商品ID查找
        product = self.product_manager.get_product_by_id(input_text)
        
        # 如果没找到，尝试通过条形码查找
        if not product:
            product = self.product_manager.get_product_by_barcode(input_text)
        
        if product:
            # 添加到购物车
            success, message = self.shopping_cart.add_item(product['id'])
            if success:
                self.result_label.text = message
                self.input_field.text = ''
                self.input_field.focus = True
            else:
                self.result_label.text = message
        else:
            self.result_label.text = "未找到该商品"
    
    def on_dismiss(self, instance):
        """弹窗关闭时更新主界面"""
        if self.update_callback:
            self.update_callback()

class ReceiptPopup(Popup):
    """收据弹窗"""
    def __init__(self, shopping_cart, **kwargs):
        super(ReceiptPopup, self).__init__(**kwargs)
        self.size_hint = (0.9, 0.9)
        self.title = "购物清单"
        self.shopping_cart = shopping_cart
        
        # 创建主布局
        main_layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
        
        # 创建收据内容
        receipt_layout = BoxLayout(orientation='vertical', spacing=5)
        
        # 标题
        receipt_layout.add_widget(Label(text='小超市结算系统', font_size=20, halign='center', size_hint_y=None, height=40))
        receipt_layout.add_widget(Label(text='购物清单', font_size=16, halign='center', size_hint_y=None, height=30))
        
        # 日期时间
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        receipt_layout.add_widget(Label(text=f'日期: {timestamp}', halign='center', size_hint_y=None, height=25))
        receipt_layout.add_widget(Label(text='-' * 40, halign='center', size_hint_y=None, height=20))
        
        # 商品列表
        items = self.shopping_cart.get_items()
        if not items:
            receipt_layout.add_widget(Label(text='购物车为空', halign='center', size_hint_y=None, height=100))
        else:
            for item in items.values():
                product = item['product']
                subtotal = product['price'] * item['quantity']
                receipt_layout.add_widget(Label(text=f"{product['name']} x{item['quantity']}", halign='left', size_hint_y=None, height=25))
                receipt_layout.add_widget(Label(text=f"    ¥{product['price']:.2f} x{item['quantity']} = ¥{subtotal:.2f}", halign='right', size_hint_y=None, height=25))
            
        receipt_layout.add_widget(Label(text='-' * 40, halign='center', size_hint_y=None, height=20))
        
        # 总计
        receipt_layout.add_widget(Label(text=f'商品总数: {self.shopping_cart.get_total_items()}', halign='left', size_hint_y=None, height=25))
        receipt_layout.add_widget(Label(text=f'总计金额: ¥{self.shopping_cart.get_total_amount():.2f}', font_size=16, halign='right', size_hint_y=None, height=30))
        
        # 添加滚动视图
        scroll_view = ScrollView()
        scroll_view.add_widget(receipt_layout)
        main_layout.add_widget(scroll_view)
        
        # 按钮布局
        button_layout = BoxLayout(size_hint_y=0.1, spacing=10)
        
        # 完成结算按钮
        finish_button = Button(text='完成结算')
        finish_button.bind(on_press=self.finish_checkout)
        button_layout.add_widget(finish_button)
        
        # 关闭按钮
        close_button = Button(text='关闭')
        close_button.bind(on_press=self.dismiss)
        button_layout.add_widget(close_button)
        
        main_layout.add_widget(button_layout)
        self.content = main_layout
    
    def finish_checkout(self, instance):
        """完成结算"""
        self.shopping_cart.clear()
        self.dismiss()
        
        # 显示结算成功提示
        success_popup = Popup(
            title="结算成功",
            content=Label(text="谢谢光临！欢迎再次惠顾！"),
            size_hint=(0.6, 0.4)
        )
        success_popup.open()
        Clock.schedule_once(success_popup.dismiss, 2)

class MainScreen(BoxLayout):
    """主屏幕"""
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'
        self.padding = 20
        self.spacing = 20
        
        # 初始化商品管理器和购物车
        self.product_manager = ProductManager()
        self.shopping_cart = ShoppingCart()
        
        # 创建标题
        title_label = Label(text='小超市结算系统', font_size=28, bold=True, size_hint_y=None, height=60)
        self.add_widget(title_label)
        
        # 创建按钮布局
        buttons_layout = GridLayout(cols=2, spacing=20, size_hint_y=0.5)
        
        # 注册新商品按钮
        register_button = Button(text='注册新商品', font_size=18)
        register_button.bind(on_press=self.open_register_product)
        buttons_layout.add_widget(register_button)
        
        # 查看所有商品按钮
        view_all_button = Button(text='查看所有商品', font_size=18)
        view_all_button.bind(on_press=self.open_view_all_products)
        buttons_layout.add_widget(view_all_button)
        
        # 扫描商品按钮
        scan_button = Button(text='扫描商品', font_size=18)
        scan_button.bind(on_press=self.open_scan_product)
        buttons_layout.add_widget(scan_button)
        
        # 结算并打印收据按钮
        checkout_button = Button(text='结算并打印收据', font_size=18)
        checkout_button.bind(on_press=self.open_checkout)
        buttons_layout.add_widget(checkout_button)
        
        self.add_widget(buttons_layout)
        
        # 创建购物车状态显示
        cart_status_layout = BoxLayout(orientation='vertical', spacing=10, size_hint_y=0.2)
        
        self.cart_items_label = Label(text=f'购物车商品数量: 0', font_size=16)
        self.cart_total_label = Label(text=f'购物车总金额: ¥0.00', font_size=16, bold=True)
        
        cart_status_layout.add_widget(self.cart_items_label)
        cart_status_layout.add_widget(self.cart_total_label)
        
        self.add_widget(cart_status_layout)
    
    def update_cart_status(self):
        """更新购物车状态显示"""
        self.cart_items_label.text = f'购物车商品数量: {self.shopping_cart.get_total_items()}'
        self.cart_total_label.text = f'购物车总金额: ¥{self.shopping_cart.get_total_amount():.2f}'
    
    def open_register_product(self, instance):
        """打开注册商品窗口"""
        popup = ProductRegistrationPopup(
            self.product_manager,
            callback=self.product_manager.load_products
        )
        popup.open()
    
    def open_view_all_products(self, instance):
        """打开查看所有商品窗口"""
        popup = ProductListPopup(self.product_manager)
        popup.open()
    
    def open_scan_product(self, instance):
        """打开扫描商品窗口"""
        popup = ScanProductPopup(
            self.product_manager,
            self.shopping_cart,
            update_callback=self.update_cart_status
        )
        popup.open()
    
    def open_checkout(self, instance):
        """打开结算窗口"""
        popup = ReceiptPopup(self.shopping_cart)
        popup.bind(on_dismiss=self.update_cart_status)
        popup.open()

class SupermarketApp(App):
    """小超市结算系统应用"""
    def build(self):
        # 设置窗口背景色
        Window.clearcolor = (0.9, 0.9, 0.9, 1)
        return MainScreen()

if __name__ == '__main__':
    SupermarketApp().run()